package com.asiainfo.hybridapp.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asiainfo.hybridapp.R;
import com.asiainfo.hybridapp.adapter.MeetingRankAdapter;
import com.asiainfo.hybridapp.adapter.PopulationRankAdapter;
import com.asiainfo.hybridapp.configs.InterfaceConfig;
import com.asiainfo.hybridapp.configs.RealInterfaceConfig;
import com.asiainfo.hybridapp.entity.MeetingRankInfo;
import com.asiainfo.hybridapp.entity.PopulationRankInfo;
import com.asiainfo.hybridapp.other.OnRequestListResult_;
import com.asiainfo.hybridapp.utils.ReloginUtil;
import com.framework.utils.CollectionUtil;
import com.framework.utils.ScreenUtils;
import com.framework.utils.Y;
import com.framework2.okhttp3.AllCookieJar;
import com.framework2.utils.JsoupUtil;
import com.framework2.utils.PicToastUtil;
import com.library.adapter_recyclerview.UniversalAdapter;
import com.library.pulltorefresh.storehouse.LocalDisplay;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * HomepageFragment
 *
 * @author YobertJomi
 * className HomepageFragment
 * created at  2017/6/15  14:35
 */
public class HomepageFragment extends Fragment {

    @BindView(R.id.tvPopulationMore)
    TextView tvPopulationMore;
    @BindView(R.id.recyclerViewTop)
    RecyclerView recyclerViewTop;
    @BindView(R.id.recyclerViewBottom)
    RecyclerView recyclerViewBottom;
    @BindView(R.id.topLinearLayout)
    LinearLayout topLinearLayout;
    @BindView(R.id.populationBar)
    RelativeLayout populationBar;
    @BindView(R.id.tvMeetingRank)
    TextView tvMeetingRank;

    private List<PopulationRankInfo> populationRankInfoList = new ArrayList<>();
    private List<MeetingRankInfo> meetingRankInfoList = new ArrayList<>();

    private UniversalAdapter adapterTop;
    private UniversalAdapter adapterBottom;

    private Context mContext;
    private View view;// infalte的布局
    private LinearLayout containerLayout;// 新建容器
    private Unbinder unbinder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        if (null == view) {
            containerLayout = new LinearLayout(mContext);
            view = inflater.inflate(R.layout.fragment_homepage, null);
            view.setMinimumHeight(((WindowManager) getActivity()
                    .getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay().getHeight());
            view.setMinimumWidth(((WindowManager) getActivity()
                    .getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay().getWidth());
            containerLayout.addView(view);
            unbinder = ButterKnife.bind(this, containerLayout);
            testData();
            initRecyclerView();
            initRecyclerViewHeight();
        } else {
            containerLayout.removeAllViews();
            containerLayout = new LinearLayout(getActivity());
            containerLayout.addView(view);
        }
        jsoupData();
        return containerLayout;
    }

    private void initRecyclerViewHeight() {
        recyclerViewTop.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (recyclerViewTop.getHeight() > 0) {
                    LinearLayout.LayoutParams layoutParams =
                            new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                    (ScreenUtils.getInstance().getScreenHeightPx(mContext) - ScreenUtils.getInstance().getStatusBarHeightPx(mContext)
                                            - topLinearLayout.getHeight() - tvMeetingRank.getHeight() - populationBar.getHeight() - ScreenUtils.getInstance().dip2px(mContext, 50) - ScreenUtils.getInstance().getScreenHeightPx(mContext) * 9 / 100) / 2);
                    recyclerViewTop.setLayoutParams(layoutParams);
                    recyclerViewBottom.setLayoutParams(layoutParams);
                    recyclerViewTop.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });
    }

    private void testData() {
        for (int i = 0; i < 6; i++) {
            PopulationRankInfo populationRankInfo = new PopulationRankInfo();
            populationRankInfo.setTitle("人口排行测试：" + i);
            populationRankInfo.setCount(500 + i);
            populationRankInfo.setDate("2017 06 16");
            populationRankInfo.setLevelUp(true);
            populationRankInfoList.add(populationRankInfo);
        }
        for (int i = 0; i < 6; i++) {
            MeetingRankInfo meetingRankInfo = new MeetingRankInfo();
            meetingRankInfo.setTitle("会议排行测试：" + i);
            meetingRankInfo.setCount1(700 + i);
            meetingRankInfo.setCount2(300 + i);
            meetingRankInfo.setCount3(900 + i);
            meetingRankInfo.setDate("2017 06 16");
            meetingRankInfo.setLevelUp(true);
            meetingRankInfoList.add(meetingRankInfo);
        }
    }

    private void jsoupData() {
        JsoupUtil.getInstance().connectGetPopulationRankList(RealInterfaceConfig.getRealBaseServerUrl() + InterfaceConfig.webMain, new AllCookieJar(mContext).loadForRequest(null), new OnRequestListResult_<PopulationRankInfo>() {

            @Override
            public void onSuccess_(List<PopulationRankInfo> list, String... msg) {
                Y.y("JsoupUtil_onSuccess" + list.size());
                for (PopulationRankInfo in : list) {
                    Y.y("JsoupUtil_onSuccess:" + in.getTitle());
                }
                if (!CollectionUtil.getInstance().isEmpty(list)) {
                    populationRankInfoList.clear();
                    populationRankInfoList.addAll(list);
                    adapterTop.notifyDataSetChanged();
                }
            }

            @Override
            public void onFail_(int code, String msg) {
                if (TextUtils.equals(msg, InterfaceConfig.reLogin)) {
                    ReloginUtil.getInstance().gotoLogin(mContext);
                }
                Y.y("JsoupUtil_onFail");
            }
        });
    }

    @SuppressWarnings("unchecked")
    private void initRecyclerView() {
        //第一种，简单的颜色，高度,水平分割线
//        HorizontalDividerItemDecoration horizontalDividerItemDecoration = new HorizontalDividerItemDecoration
//        (getActivity());
//        horizontalDividerItemDecoration.setColor(getActivity(), R.color.white);
//        horizontalDividerItemDecoration.setDividerHeightPx(ScreenUtils.getInstance().dip2px(getActivity(), 1));
//        recyclerViewTop.addItemDecoration(horizontalDividerItemDecoration);
//        recyclerViewBottom.addItemDecoration(horizontalDividerItemDecoration);
        recyclerViewTop.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerViewBottom.setLayoutManager(new LinearLayoutManager(getActivity()));
        if (CollectionUtil.getInstance().isEmpty(populationRankInfoList)) {
//            showEmptyView("");
        }
        if (null == adapterTop) {
            adapterTop = new PopulationRankAdapter(getActivity(), R.layout.listitem_population_rank,
                    populationRankInfoList);
            recyclerViewTop.setAdapter(adapterTop);
        }
        if (null == adapterBottom) {
            adapterBottom = new MeetingRankAdapter(getActivity(), R.layout.listitem_meeting_rank, meetingRankInfoList);
            recyclerViewBottom.setAdapter(adapterBottom);
        }
    }

    private void showEmptyView(CharSequence emptyString) {
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.empty_view, null);
        if (!TextUtils.isEmpty(emptyString)) {
            ((TextView) inflate.findViewById(com.library.pulltorefresh.R.id.tv_empty)).setText(emptyString);
        } else {
            ((TextView) inflate.findViewById(com.library.pulltorefresh.R.id.tv_empty)).setText("");
        }
        inflate.setMinimumWidth(LocalDisplay.getScreenWidthPixels(getActivity()));
        inflate.setMinimumHeight(LocalDisplay.getScreenHeightPixels(getActivity()));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.tvPopulationMore)
    public void onViewClicked() {
        PicToastUtil.showPicToast(getActivity(), "查看更多");
    }
}
